package com.sl.au.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.sl.au.entity.GeoLocation;
import com.sl.au.repository.GeoLocationRepository;
import com.sl.au.service.GeoLocationService;
import com.sl.utils.BaiduAPI;
import com.sl.utils.CoordsTransform;

@RestController
@RequestMapping(value = "/ui/location")
public class GeoLocationController extends BaseController {

	@Autowired
	GeoLocationRepository geolocationRepository;
	@Autowired
	GeoLocationService geoLocationService;

	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> location(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String userId = this.getMyAccount().getUser().getId();
		List<GeoLocation> geoLocations = geoLocationService.getGeoLocationPage(start, length, userId, null, null);
		map.put("data", geoLocations);
		return map;
	}

	/**
	 * 保存手机发送过来的位置坐标
	 * 
	 * @param location
	 * @return
	 */
	@RequestMapping(value = "save", method = RequestMethod.PUT)
	private Map<String, Object> saveLocation(@RequestBody GeoLocation location) {
		Map<String, Object> map = new HashMap<>();
		int code = -1;
		if (null != location) {
			//转化坐标
			double[] res=CoordsTransform.wgs2bd( location.getLongitude(),location.getLatitude());
			try {
				//获取位置address
				Map<String, String> json = BaiduAPI.testPost(String.valueOf(res[1]), String.valueOf(res[0]));
				location.setPlace(json.get("address"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			code = 0;
			this.geolocationRepository.save(location);
		}
		map.put("place", location.getPlace());
		map.put("code", code);
		return map;
	}

}
